package com.shanling.shanlingcontroller.ui.fragment;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import com.badoo.mobile.util.WeakHandler;
import com.db.chart.model.LineSet;
import com.db.chart.view.AxisController;
import com.db.chart.view.ChartView;
import com.db.chart.view.LineChartView;
import com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar;
import com.qualcomm.qti.libraries.gaia.GAIA;
import com.shanling.shanlingcontroller.CustomApplication;
import com.shanling.shanlingcontroller.R;
import com.shanling.shanlingcontroller.base.BaseLazyFragment;
import com.shanling.shanlingcontroller.bean.Constants;
import com.shanling.shanlingcontroller.bean.EQBean;
import com.shanling.shanlingcontroller.bean.EventCenter;
import com.shanling.shanlingcontroller.bean.Filter;
import com.shanling.shanlingcontroller.bean.ParameterType;
import com.shanling.shanlingcontroller.services.csr.CustomEqualizerGaiaManager;
import com.shanling.shanlingcontroller.utils.EQBeansUtils;
import com.shanling.shanlingcontroller.utils.ThreadPoolProxyFactory;
import com.shanling.shanlingcontroller.utils.ToastUtils;
import com.shanling.shanlingcontroller.view.EQPopupWindow;
import com.shanling.shanlingcontroller.view.NoChooseDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ch1 on 2019/11/30.
 */

public class EQFragment extends BaseLazyFragment implements SeekBar.OnSeekBarChangeListener, CustomEqualizerGaiaManager.GaiaManagerListener, EQPopupWindow.ItemOnClickInterface {
    @BindView(R.id.lineChart)
    LineChartView chart;
    @BindView(R.id.tv_Preset)
    TextView tvPreset;
    @BindView(R.id.tv_Reset)
    TextView tvReset;
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.seekBar1)
    VerticalSeekBar seekBar1;
    @BindView(R.id.seekBar2)
    VerticalSeekBar seekBar2;
    @BindView(R.id.seekBar3)
    VerticalSeekBar seekBar3;
    @BindView(R.id.seekBar4)
    VerticalSeekBar seekBar4;
    @BindView(R.id.seekBar5)
    VerticalSeekBar seekBar5;
    @BindView(R.id.seekBar6)
    VerticalSeekBar seekBar6;
    @BindView(R.id.seekBar7)
    VerticalSeekBar seekBar7;
    @BindView(R.id.seekBar8)
    VerticalSeekBar seekBar8;
    @BindView(R.id.seekBar9)
    VerticalSeekBar seekBar9;
    @BindView(R.id.seekBar10)
    VerticalSeekBar seekBar10;
    LineSet dataset;
    Paint paint;
    float[] points;
    @BindView(R.id.tv_eq1)
    TextView tvEq1;
    @BindView(R.id.tv_eq2)
    TextView tvEq2;
    @BindView(R.id.tv_eq3)
    TextView tvEq3;
    @BindView(R.id.tv_eq4)
    TextView tvEq4;
    @BindView(R.id.tv_eq5)
    TextView tvEq5;
    @BindView(R.id.tv_eq6)
    TextView tvEq6;
    @BindView(R.id.tv_eq7)
    TextView tvEq7;
    @BindView(R.id.tv_eq8)
    TextView tvEq8;
    @BindView(R.id.tv_eq9)
    TextView tvEq9;
    @BindView(R.id.tv_eq10)
    TextView tvEq10;
    private String data[] = {"31", "62", "125", "250", "500", "1K", "2K", "4K", "8K", "16k"};
    CustomEqualizerGaiaManager customEqualizerGaiaManager;
    private boolean isOpen;
    private int bond=1;
    private NoChooseDialog noChooseDialog;
    private EQPopupWindow eqPopupWindow;
    private List<EQBean> eqBeans;
    private int check=0;
    private boolean isSend;
    private Runnable runnable;
    @Override
    protected void onLazyLoad() {
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       @GAIA.Transport int transport = GAIA.Transport.BR_EDR;
        customEqualizerGaiaManager=new CustomEqualizerGaiaManager(this, transport);
        EventBus.getDefault().register(this);
        noChooseDialog = new NoChooseDialog(getContext(), R.style.myDialog, R.string.Equalizer, R.string.dialog_incorrect_state_message, R.string.confirm, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                noChooseDialog.dismiss();
            }
        });
        eqBeans= EQBeansUtils.getEQbeans(getContext(),true);
        eqPopupWindow=new EQPopupWindow(getActivity());
        eqPopupWindow.setItemOnClickInterface(this);

    }

    @Override
    public void onResume() {
        super.onResume();
        getInformationFromDevice();
    }

    private void getInformationFromDevice() {
        customEqualizerGaiaManager.getPreset();
        customEqualizerGaiaManager.getActivationState();
        for (int i = 0; i <10 ; i++) {
            int band=i+1;
            customEqualizerGaiaManager.getEQParameter(band ,2);
        }
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_eq;
    }

    @Override
    protected void initViewsAndEvents() {
        paint = new Paint();
        dataset = new LineSet();
        points = new float[10];
        for (int i = 0; i < 10; i++) {
            points[i] = 12;
            dataset.addPoint(data[i], points[i]);
        }
        paint.setColor(Color.parseColor("#CAB487"));
        paint.setStrokeWidth((float) (1.10 * 1.0));
        dataset.setColor(Color.parseColor("#CAB487"));
        dataset.setSmooth(true);
        dataset.setThickness(2);
        chart.setXAxis(false);
        chart.setYAxis(false);
        chart.setYLabels(AxisController.LabelPosition.NONE);
        chart.setXLabels(AxisController.LabelPosition.NONE);
        chart.setGrid(ChartView.GridType.NONE, 7, 10, paint);
        chart.setAxisBorderValues(0, 24);
        chart.addData(dataset);
        chart.show();
        seekBar1.setOnSeekBarChangeListener(this);
        seekBar2.setOnSeekBarChangeListener(this);
        seekBar3.setOnSeekBarChangeListener(this);
        seekBar4.setOnSeekBarChangeListener(this);
        seekBar5.setOnSeekBarChangeListener(this);
        seekBar6.setOnSeekBarChangeListener(this);
        seekBar7.setOnSeekBarChangeListener(this);
        seekBar8.setOnSeekBarChangeListener(this);
        seekBar9.setOnSeekBarChangeListener(this);
        seekBar10.setOnSeekBarChangeListener(this);
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {

    }

    @OnClick({R.id.tv_Preset, R.id.tv_Reset})
    public void onViewClicked(View view) {
        if(!isOpen){
            ToastUtils.showToast(getActivity(),R.string.eq_isnot_open);
            return;
        }
        switch (view.getId()) {
            case R.id.tv_Preset:
                eqPopupWindow.show(eqBeans,tvPreset);
                break;
            case R.id.tv_Reset:
                seekBar1.setProgress(720);
                seekBar2.setProgress(720);
                seekBar3.setProgress(720);
                seekBar4.setProgress(720);
                seekBar5.setProgress(720);
                seekBar6.setProgress(720);
                seekBar7.setProgress(720);
                seekBar8.setProgress(720);
                seekBar9.setProgress(720);
                seekBar10.setProgress(720);
                for (int i = 0; i < eqBeans.size(); i++) {
                    eqBeans.get(i).setCheck(false);
                }
                eqBeans.get(0).setCheck(true);
                customEqualizerGaiaManager.setPreset(1);
                for (int i = 0; i <10 ; i++) {
                    int band=i+1;
                    customEqualizerGaiaManager.setEQParameter(band ,2,0);
                }
                break;
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        int id = seekBar.getId();
        double value =(progress - 720)/(double)60;
        float point=progress/60;
        switch (id) {
            case R.id.seekBar1:
                points[0] = point;
                setValue(value,tvEq1);
                break;
            case R.id.seekBar2:
                points[1] = point;
                setValue(value,tvEq2);
                break;
            case R.id.seekBar3:
                points[2] = point;
                setValue(value,tvEq3);
                break;
            case R.id.seekBar4:
                points[3] = point;
                setValue(value,tvEq4);
                break;
            case R.id.seekBar5:
                points[4] = point;
                setValue(value,tvEq5);
                break;
            case R.id.seekBar6:
                points[5] = point;
                setValue(value,tvEq6);
                break;
            case R.id.seekBar7:
                points[6] = point;
                setValue(value,tvEq7);
                break;
            case R.id.seekBar8:
                points[7] = point;
                setValue(value,tvEq8);
                break;
            case R.id.seekBar9:
                points[8] = point;
                setValue(value,tvEq9);
                break;
            case R.id.seekBar10:
                points[9] = point;
                setValue(value,tvEq10);
                break;
        }
        dataset.updateValues(points);
        chart.notifyDataUpdate();
    }

    private void  setValue(double value,TextView textView){
        DecimalFormat myformat=new DecimalFormat("0.0");
        textView.setText(myformat.format(value));
    }


    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        if(check!=0){
            for (int i = 0; i <eqBeans.size() ; i++) {
                eqBeans.get(i).setCheck(false);
            }
            eqBeans.get(0).setCheck(true);
            customEqualizerGaiaManager.setPreset(1);
        }
        int id = seekBar.getId();
        int value=93;
        Log.e("weiyu","开始活动");
        switch (id) {
            case R.id.seekBar1:
                bond=1;
                value=93;
                break;
            case R.id.seekBar2:
                bond=2;
                value=186;
                break;
            case R.id.seekBar3:
                bond=3;
                value=375;
                break;
            case R.id.seekBar4:
                bond=4;
                value=750;
                break;
            case R.id.seekBar5:
                bond=5;
                value=1500;
                break;
            case R.id.seekBar6:
                bond=6;
                value=3000;
                break;
            case R.id.seekBar7:
                bond=7;
                value=6000;
                break;
            case R.id.seekBar8:
                bond=8;
                value=12000;
                break;
            case R.id.seekBar9:
                bond=9;
                value=24000;
                break;
            case R.id.seekBar10:
                bond=10;
                value=48000;
                break;
        }
        Log.e("weiyu","参数"+bond+"value"+value);
        customEqualizerGaiaManager.setEQParameter(bond,1,value);
    }
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int id = seekBar.getId();
        int progress=seekBar.getProgress();
        int value=progress-720;
        switch (id) {
            case R.id.seekBar1:
                bond=1;
                break;
            case R.id.seekBar2:
                bond=2;
                break;
            case R.id.seekBar3:
                bond=3;
                break;
            case R.id.seekBar4:
                bond=4;
                break;
            case R.id.seekBar5:
                bond=5;
                break;
            case R.id.seekBar6:
                bond=6;
                break;
            case R.id.seekBar7:
                bond=7;
                break;
            case R.id.seekBar8:
                bond=8;
                break;
            case R.id.seekBar9:
                bond=9;
                break;
            case R.id.seekBar10:
                bond=10;
                break;
        }
      customEqualizerGaiaManager.setEQParameter(bond,2,value);
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()){
            case  Constants.GAIA_PACKET:
                byte[] data = (byte[]) eventCenter.getData();
                customEqualizerGaiaManager.onReceiveGAIAPacket(data);
                break;
            case Constants.SET_EQ_SELECTED:
               isOpen= (boolean) eventCenter.getData();
                eQisOpen();
                customEqualizerGaiaManager.setActivationState(isOpen);
                break;
        }
    }

    public void eQisOpen(){

        if(isOpen){
            seekBar1.setEnabled(true);
            seekBar2.setEnabled(true);
            seekBar3.setEnabled(true);
            seekBar4.setEnabled(true);
            seekBar5.setEnabled(true);
            seekBar6.setEnabled(true);
            seekBar7.setEnabled(true);
            seekBar8.setEnabled(true);
            seekBar9.setEnabled(true);
            seekBar10.setEnabled(true);
        }else {
            ToastUtils.showToast(getActivity(),R.string.eq_isnot_open);
            seekBar1.setEnabled(false);
            seekBar2.setEnabled(false);
            seekBar3.setEnabled(false);
            seekBar4.setEnabled(false);
            seekBar5.setEnabled(false);
            seekBar6.setEnabled(false);
            seekBar7.setEnabled(false);
            seekBar8.setEnabled(false);
            seekBar9.setEnabled(false);
            seekBar10.setEnabled(false);
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        eqPopupWindow.dissmiss();
        noChooseDialog.dismiss();
        noChooseDialog=null;
        if(runnable!=null){
            ThreadPoolProxyFactory.getNormalThreadPoolProxy().remove(runnable);
        }
    }

    @Override
    public boolean sendGAIAPacket(byte[] packet) {
        runnable=new Runnable() {
            @Override
            public void run() {
                isSend=CustomApplication.getInstance().getmGAIABREDRProvider().sendGAIAUpgradePacket(packet, true) ;
                Log.e("weiyu","eq发送"+isSend);
            }
        };
        ThreadPoolProxyFactory.getNormalThreadPoolProxy().execute(runnable);

        return true;
    }
    @Override
    public void onControlNotSupported() {

    }
    @Override
    public void onGetMasterGain(int value) {

    }
    @Override
    public void onGetFilter(int band, Filter filter) {


    }
    @Override
    public void onGetFrequency(int band, int value) {
        Log.e("weiyu","Frequency"+"bond"+band+"//"+value);

    }
    @Override
    public void onGetGain(int band, int value) {
        Log.e("weiyu","onGetGain"+"bond"+band+"//"+value);
        if(check==0){
            int progress=value;
            if(value>720){
                progress=720-(65536-value);
            }else {
                progress=value+720;
            }
            if(value==13){
                progress=720;
            }
            switch (band){
                case 1:
                    seekBar1.setProgress(progress);
                    break;
                case 2:
                    seekBar2.setProgress(progress);
                    break;
                case 3:
                    seekBar3.setProgress(progress);
                    break;
                case 4:
                    seekBar4.setProgress(progress);
                    break;
                case 5:
                    seekBar5.setProgress(progress);
                    break;
                case 6:
                    seekBar6.setProgress(progress);
                    break;
                case 7:
                    seekBar7.setProgress(progress);
                    break;
                case 8:
                    seekBar8.setProgress(progress);
                    break;
                case 9:
                    seekBar9.setProgress(progress);
                    break;
                case 10:
                    seekBar10.setProgress(progress);
                    break;
            }
        }
    }
    @Override
    public void onGetQuality(int band, int value) {

    }


    @Override
    public void onIncorrectState() {
        Log.e("weiyu","没有播放"+isOnRusme);
        noChooseDialog.show();
    }


    @Override
    public void onGetControlActivationState(boolean activated) {
            isOpen=activated;
            eQisOpen();
            EventBus.getDefault().post(new EventCenter<>(Constants.GET_EQ_SELECTED,activated));
    }

    @Override
    public void onGetPreset(int preset) {
        Log.e("weiyu","preset"+preset);
        for (int i = 0; i <eqBeans.size() ; i++) {
            eqBeans.get(i).setCheck(false);
        }
        if(preset==1){
            check=0;
            eqBeans.get(0).setCheck(true);
            return;
        }
        int[] eqDate = new int[10];
        switch (preset){
            case 0:
                check=1;
                eqBeans.get(1).setCheck(true);
                eqDate=eqBeans.get(1).getEqDate();
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
                check=preset;
                eqBeans.get(preset).setCheck(true);
                eqDate=eqBeans.get(preset).getEqDate();
                break;
        }
        setProgress(eqDate);
    }

    private void setProgress(  int[] eqDate){
        seekBar1.setProgress(eqDate[0]);
        seekBar2.setProgress(eqDate[1]);
        seekBar3.setProgress( eqDate[2]);
        seekBar4.setProgress(eqDate[3]);
        seekBar5.setProgress( eqDate[4]);
        seekBar6.setProgress( eqDate[5]);
        seekBar7.setProgress( eqDate[6]);
        seekBar8.setProgress( eqDate[7]);
        seekBar9.setProgress( eqDate[8]);
        seekBar10.setProgress( eqDate[9]);
    }

    @Override
    public void onItemClick(View view, int position) {
        EQBean eqBean = eqBeans.get(position);
        int[] eqDate = eqBean.getEqDate();
        check=position;
        if(position!=0){
            eqBeans.get(0).setEqDate(eqDate);
        }
        int  mPreset=0;
        switch (position){
            case 0:
                mPreset=1;
                break;
            case 1:
                mPreset=0;
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
                mPreset=position;
                break;
        }
        setProgress(eqBean.getEqDate());
      customEqualizerGaiaManager.setPreset(mPreset);
        for (int i = 0; i <10 ; i++) {
            int band=i+1;
           int value= getValue(band);
            Log.e("weiyu","参数"+band+"value"+value);
           customEqualizerGaiaManager.setEQParameter(band ,2,value);
        }
    }

    private int  getValue(int bond) {
        int value=0;
        switch (bond){
            case 1:
                value= seekBar1.getProgress()- 720;
                break;
            case 2:
                value= seekBar2.getProgress()-720;;
                break;
            case 3:
                value= seekBar3.getProgress()- 720;
                break;
            case 4:
                value= seekBar4.getProgress()- 720;
                break;
            case 5:
                value= seekBar5.getProgress()- 720;
                break;
            case 6:
                value= seekBar6.getProgress()- 720;
                break;
            case 7:
                value= seekBar7.getProgress()- 720;
                break;
            case 8:
                value= seekBar8.getProgress()- 720;
                break;
            case 9:
                value= seekBar9.getProgress()- 720;
                break;
            case 10:
                value= seekBar10.getProgress()- 720;
                break;
        }
        return value;
    }


}
